<template>
  <div :class="isBeyondLimit ? 'upload limit-upload': 'upload'">
    {{readonly}}
    <el-upload
      action
      ref="upload"
      :class="readonly === undefined ? '':'readonly'"
      :list-type="type ? type : 'picture-card'"
      :file-list="fileList__"
      :accept="accept"
      :limit="limitNumber"
      :multiple="multiple"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" v-if="type === 'picture-card' || !type"></i>
      <el-button
        v-else
        size="small"
        class="upload-button"
        type="primary"
        :disabled="isBeyondLimit"
      >点击上传</el-button>
    </el-upload>
    <viewer v-show="false" :images="fileList__preview">
      <img
        v-for="(src,index) in fileList__preview"
        width="100"
        :ref="'prevFile'+ index"
        :src="src"
        :key="index"
      />
    </viewer>
  </div>
</template>

<script>
import * as qiniu from "qiniu-js";
import api from "@/api/apiPath";
import excel from "@/assets/icon/excel.png";
import pdf from "@/assets/icon/pdf.png";
import word from "@/assets/icon/word.png";
import { log } from "util";

const ICON = {
  excel,
  pdf,
  word
};

export default {
  name: "upload",
  created() {},
  mounted() {
    if (this.accept) {
      let acceptMap = {};
      let acceptList = this.accept.split(",");
      acceptList.forEach(item => {
        acceptMap[item.trim()] = true;
      });
      this.acceptMap = acceptMap;
    }
  },
  components: {},
  props: [
    "fileList",
    "limit",
    "multiple",
    "accept",
    "type",
    "readonly",
    "size"
  ],
  watch: {
    limit: {
      handler(limit) {
        //判断是否是只读
        if (this.readonly !== undefined) {
          this.isBeyondLimit = true;
        }
        if (limit) {
          this.limitNumber = limit;
        }
      },
      immediate: true
    },
    fileList: {
      handler(newList) {
        if (newList) {
          let fileList__ = [];
          newList.forEach(item => {
            this.fileIconDisplay(
              item.slice(item.lastIndexOf(".")),
              fileType => {
                if (fileType === "image") {
                  fileList__.push({
                    url: item,
                    name: this.filterName(item)
                  });
                } else {
                  fileList__.push({
                    url: ICON[fileType],
                    realUrl: item,
                    name: this.filterName(item)
                  });
                }
              }
            );
          });
          this.fileList__ = fileList__;
        }
      },
      immediate: true
    },
    fileList__: {
      handler(newList) {
        if (this.limit) {
          this.isBeyondLimit = newList.length >= this.limit;
        }
        let fileList__preview = [];
        newList.forEach(item => {
          if (!item.realUrl && !item.fileType) {
            fileList__preview.push(item.url);
          }
        });
        this.fileList__preview = fileList__preview;
      },
      immediate: true
    }
  },
  computed: {},
  data() {
    return {
      isBeyondLimit: false,
      limitNumber: 9999,
      fileList__: [],
      fileList__preview: [],
      acceptMap: {},
      fileType2suffix: {
        "image/jpeg": ".jpeg",
        "image/jpeg": ".jpg",
        "image/png": ".png",
        "image/bmp": ".bmp",
        "image/gif": ".gif",
        "application/pdf": ".pdf",
        "application/msword": ".doc",
        "application/vnd.ms-excel": ".xls",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
          ".docx",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
          ".xlsx"
      },
      fileType: {
        image: [".jpeg", ".jpg", ".png", ".bmp", ".gif"],
        word: [".doc", ".docx"],
        excel: [".xls", ".xlsx"],
        pdf: [".pdf"]
      }
    };
  },
  methods: {
    filterName(name) {
      let reg = /\d{13}\-\d{4}\/cms\//;
      let prefix = name.match(reg);
      return prefix ? name.slice(prefix.index + 23, name.length) : name;
    },
    handleExceed() {
      this.$message.warning("文件上传个数超出限制！");
    },
    handleRemove(file, fileList__) {
      this.fileList__ = fileList__;
      // 新添加的不触发emit
      if (!file.raw) {
        this.$emit("selectedFile", this.fileList__);
      }
    },
    removeFile(name) {
      if (this.fileList__.length != 0) {
        for (let i = 0; i < this.fileList__.length; i++) {
          if (name == this.fileList__[i].name) {
            this.fileList__.splice(i, 1);
          }
        }
      }
    },
    handlePictureCardPreview(file) {
      if (file.fileType) {
        if (file.fileType === "pdf") {
          const myWindow = window.open("");
          myWindow.document.write(
            `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>${file.file.name} - PDF预览</title><style>html,body{width: 100%;height: 100%;} *{margin: 0;padding: 0;}</style></head><body>`
          );
          myWindow.document.write(
            `<iframe width="100%" height="99%" style="border-width:0px" src="${file.fileBase64}"></iframe>`
          );
          myWindow.document.write(`</body></html>`);
        } else {
          this.$confirm(
            `未保存到服务器的word、excel文件不支持在线预览！如需预览将会把文件下载到本地, 是否继续预览文件 ${file.file.name} ?`,
            "提示",
            {
              confirmButtonText: "下载预览",
              cancelButtonText: "取消",
              type: "warning"
            }
          )
            .then(() => {
              window.open(file.fileBase64, file.file.name);
            })
            .catch(() => {});
        }
        return false;
      }
      const prevIndex = this.fileList__preview.indexOf(file.url);
      if (prevIndex > -1) {
        setTimeout(() => {
          this.$refs["prevFile" + prevIndex][0].click();
        });
      } else {
        const fileSuffix = file.realUrl.slice(file.realUrl.lastIndexOf("."));
        if (fileSuffix === ".pdf") {
          window.open(file.realUrl);
        } else {
          window.open(
            `https://view.officeapps.live.com/op/view.aspx?src=${file.realUrl}`
          );
        }
      }
    },
    beforeUpload(file) {
      let regEn = /[\/:*?"<> |]/im;
      if(regEn.test(file.name)) {
        this.$message.warning(`该（${file.name}）附件名称包含特殊字符（[\/:*?"<> |]），请修改后重新上传！`);
        return false
      }
      if (this.isBeyondLimit) {
        this.$message.warning("禁止上传！");
        return false;
      }
      let currentSuffix = this.fileType2suffix[file.type];
      if (this.accept && !this.acceptMap[currentSuffix]) {
        this.$message.warning("上传的文件只能是 " + this.accept + " 格式!");
        return false;
      }
      if (this.size) {
        let isLtSize = file.size / 1024 / 1024 < this.size;
        if (!isLtSize) {
          this.$message.warning(`上传图片大小不能超过 ${this.size}MB!`);
          return false;
        }
      }

      this.fileIconDisplay(currentSuffix, fileType => {
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onloadend = () => {
          if (fileType === "image") {
            this.fileList__.push({
              url: reader.result,
              file: file,
              name: file.name
            });
          } else {
            this.fileList__.push({
              url: ICON[fileType],
              file: file,
              fileType,
              fileBase64: reader.result,
              name: file.name
            });
          }
        };
        this.$emit("selectedFile", file);
      });
      return false;
    },
    uploadToken() {
      return this.axios.post(api.UPLOADTOKEN, {});
    },
    async submit() {
      try {
        let token = "";
        if (this.fileList__.length) {
          token = await this.uploadToken();
        }

        let qiuniuPromise = [];
        this.fileList__.forEach(item => {
          qiuniuPromise.push(this.uploadQiniu(token.data.data, item));
          // qiuniuPromise.push(this.uploadQiniu(token, item))
        });
        return Promise.all(qiuniuPromise);
      } catch (e) {
        console.log(e);
        return Promise.reject(e);
      }
    },
    fileIconDisplay(currentSuffix, callback) {
      for (let key in this.fileType) {
        if (this.fileType[key].indexOf(currentSuffix) > -1) {
          callback(key);
        }
      }
    },
    uploadQiniu(token, item) {
      return new Promise((resolve, reject) => {
        const file = item.file;
        if (file) {
          const fileName = file.name;
          const uploadTime = new Date().getTime();
          const randomNumber = (Math.random() + "").slice(3, 7);
          const putExtra = {
            fname: fileName,
            params: {},
            mimeType: null
          };
          const config = { useCdnDomain: true };
          const observable = qiniu.upload(
            file,
            `${uploadTime}-${randomNumber}/cms/${fileName}`,
            token.imgToken,
            putExtra,
            config
          );
          const that = this;
          let loading = null;
          observable.subscribe(
            function() {
              loading = that.$loading({
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)"
              });
            },
            function() {},
            function(res) {
              loading.close();
              resolve(token.qiniuUrl + res.key);
            }
          );
        } else {
          resolve(item.realUrl || item.url);
        }
      });
    }
  }
};
</script>
<style lang="stylus">
.limit-upload {
  .el-upload--picture-card {
    display: none;
  }

  .upload-button {
    display: none;
  }
}

.upload {
  .el-upload-list--picture-card {
    > li {
      // padding-bottom: 30px;
      position: relative;
    }

    .el-upload-list__item-name {
      width: 148px;
      position: absolute;
      bottom: -3px;
      font-size: 10px;
      display: block;
      margin-right: 0;
      text-align: center;
      padding-left: 0;

      i {
        display: none;
      }
    }
  }

  .el-icon-close-tip {
    display: none !important;
  }

  .readonly {
    .el-upload-list__item-actions:hover {
      .el-upload-list__item-delete {
        display: none;
      }
    }
  }

  .name-list {
    span {
      text-align: center;
      display: inline-block;
      word-wrap: break-word;
      vertical-align: middle;
      width: 148px;
      margin-right: 8px;
      white-space: normal;
      color: #606266;
    }
  }
}
</style>
